package com.marui.ch9.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

public class SingleDemo {
    private static AtomicBoolean isHappened = new AtomicBoolean(false);
    // 请求总数
    public static int clientTotal = 50;

    // 同时并发执行的线程数
    public static int threadTotal = 2;

    public static String state="01";

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
       // final Semaphore semaphore = new Semaphore(threadTotal);
        //final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                   // semaphore.acquire();
                    if (isHappened.compareAndSet(false, true)) {
                        System.out.println("execute");
                       state="02";
                    }
                   // semaphore.release();
                    if("02".equals(state)){
                        System.out.println("--------------------------02");
                    }
                    if("01".equals(state)){
                        System.out.println("--------------------------01");
                    }


                } catch (Exception e) {
                }
               // countDownLatch.countDown();
            });
        }
       // countDownLatch.await();
        executorService.shutdown();
        System.out.println("isHappened:{}" + isHappened.get());
        System.out.println(new SingleDemo().getState());
    }

    //该方法只会执行一次
    private static void test() {
        if (isHappened.compareAndSet(false, true)) {
            System.out.println("execute");
            new SingleDemo().setState("02");
        }
    }

}
